var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var estado = null;

function inicializarMapa(latitud, longitud){
    google.maps.event.addDomListener(window, 'load', initialize);
    initialize(latitud, longitud);
}
	
function initialize(lat, long) {
  // Instantiate a directions service.
  directionsService = new google.maps.DirectionsService();

  if (lat && long){
	  var posicion = new google.maps.LatLng(lat,long);
	  var mapOptions = {
	    zoom: 11,
	    mapTypeId: google.maps.MapTypeId.ROADMAP,
	    center: posicion
	  }
	  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	  // Create a renderer for directions and bind it to the map.
	  if (map){
		  var rendererOptions = {
		    map: map
		  }
		  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
		
		  // Instantiate an info window to hold step text.
		  stepDisplay = new google.maps.InfoWindow();
	  }
  }
}

function calcRoute(origen, destino) {
  // First, remove any existing markers from the map.
  for (var i = 0; i < markerArray.length; i++) {
    markerArray[i].setMap(null);
  }

  // Now, clear the array itself.
  markerArray = [];

  // Retrieve the start and end locations and create
  // a DirectionsRequest using WALKING directions.
  var start = origen;
  var end = destino;
  if (start && end){
	  var request = {
	      origin: start,
	      destination: end,
	      travelMode: google.maps.TravelMode.DRIVING
	  };
	
	  // Route the directions and pass the response to a
	  // function to create markers for each step.
	  directionsService.route(request, function(response, status) {
		estado = status;
	    if (status == google.maps.DirectionsStatus.OK) {
	      var warnings = document.getElementById('warnings_panel');
	      warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
	      directionsDisplay.setDirections(response);
//	      showSteps(response);
	    }
	  });
	  
	  calculateDistances($("#origen").val(), $("#destino").val());
	}
}

function showSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  var myRoute = directionResult.routes[0].legs[0];

  for (var i = 0; i < myRoute.steps.length; i++) {
    var marker = new google.maps.Marker({
      position: myRoute.steps[i].start_point,
      map: map
    });
    attachInstructionText(marker, myRoute.steps[i].instructions);
    markerArray[i] = marker;
  }
}

function attachInstructionText(marker, text) {
  google.maps.event.addListener(marker, 'click', function() {
    // Open an info window when the marker is clicked on,
    // containing the text of the step.
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

function sumar(elemento, valor, minimo, maximo){
	var valorInt = parseInt(elemento.val());
	valorInt = valorInt + valor
	if (valorInt>=minimo && valorInt <= maximo){
		elemento.val(valorInt);
	}
}

function calculateDistances(origin, destination, valor) {
	if (origin != '' && destination != '') {
		var service = new google.maps.DistanceMatrixService();
		var travel = google.maps.TravelMode.DRIVING;
		if (valor){
			travel = google.maps.TravelMode.WALKING;
		}
		service.getDistanceMatrix({
			origins : [ origin ],
			destinations : [ destination ],
			travelMode : travel,
			// unitSystem: google.maps.UnitSystem.METRIC,
			avoidHighways : false,
			avoidTolls : false
		}, function (response, status){
			if (status != google.maps.DistanceMatrixStatus.OK) {
				alert('Error was: ' + status);
			} else {
				var origins = response.originAddresses;
				var destinations = response.destinationAddresses;
				$('#distancia').html();
				
				if (origins!='' && destinations!=''){
					var distancia = 0;
					for ( var i = 0; i < origins.length; i++) {
						var results = response.rows[i].elements;
						for ( var j = 0; j < results.length; j++) {
							if (valor!='true'){
								$('#distancia').html(results[j].distance.text + "<br><br>" +  results[j].duration.text);
							}else{
								$("#distanciaInicial").val(results[j].distance.value);
							}
						}
					}
				}
			}
		});
	}
}

//function callback(response, status) {
//	if (status != google.maps.DistanceMatrixStatus.OK) {
//		alert('Error was: ' + status);
//	} else {
//		var origins = response.originAddresses;
//		var destinations = response.destinationAddresses;
//		$('#distancia').html();
//		
//		if (origins!='' && destinations!=''){
//			var distancia = 0;
//			for ( var i = 0; i < origins.length; i++) {
//				var results = response.rows[i].elements;
//				for ( var j = 0; j < results.length; j++) {
//						$('#distancia').html(results[j].distance.text + "<br><br>" +  results[j].duration.text);
//				}
//			}
//		}
//	}
//}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

function getLocation() {
	if (navigator.geolocation) {
	  navigator.geolocation.getCurrentPosition(showPosition);
	} else {
	  alert("Geolocation is not supported by this browser.");
	}
}

function showPosition(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  map.setCenter(new google.maps.LatLng(lat, lng));
}